# -*- coding:utf-8 -*-
import flask
from flask import Blueprint, request, render_template, redirect, flash, url_for, session
from apps.account.forms import RegisterForm, LoginForm, UserUpdateForm, UpdatePasswordForm
from apps.ext import db
from apps.models import User, Kind, News

account = Blueprint("account", __name__)


@account.route("/register/", methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        form = RegisterForm()
        return render_template('account/register/register.html', form=form)
    else:
        form = RegisterForm(formdata=request.form)
        if form.validate():
            # 验证用户是否注册
            is_register = form.is_register()
            if not is_register:
                from apps.ext import images, get_file_name
                if 'img' in request.files:
                    image = request.files['img']
                    file_name = images.save(image, folder='', name=get_file_name(image.filename))
                    img_url = images.url(file_name)
                    # 发送邮件验证
                    form.send_email()
                    # 创建用户
                    form.create_user(img_url)
                    flash('注册成功，请移步至邮箱点击激活')
                    return redirect(url_for('account.login'))
                else:
                    form.errors["img"] = ["未上传头像"]
            else:
                form.errors["is_register"] = [is_register]
        else:
            print(form.errors)
        return render_template('account/register/register.html', form=form, errors=form.errors.values())


@account.route("/verify/", methods=['GET', 'POST'])
def register_verify():
    """
    邮箱验证
    :param request:
    :return:
    """
    username = session.get("username")
    print(username)
    if username:
        user = User.query.filter_by(username=username).first()
        user.is_active = 1
        db.session.commit()
        flash("激活成功，跳转登录页面")
    return redirect(url_for('account.login'))


@account.route("/login/", methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        form = LoginForm()
        return render_template('account/login/login.html', form=form)
    else:
        form = LoginForm(formdata=request.form)
        if form.validate():
            # 判断用户是否注册
            can_login = form.can_login()
            if can_login:
                next = flask.request.args.get('next')
                return redirect(next or '/')
            else:
                form.errors["can_login"] = ["用户未注册或账号密码错误"]
    return render_template("account/login/login.html", form=form, errors=form.errors.values())


@account.route("/login_out/")
def login_out():
    user_id = session['user']['user_id']
    user = User.query.filter_by(user_id=user_id).first()
    user.is_login = 0
    db.session.commit()
    del session['user']
    return redirect('/')


@account.route("/center/", methods=['GET', 'POST'])
def center():
    user_session = session.get('user')
    user = User.query.get(user_session['user_id'])
    if request.method == 'GET':
        form = UserUpdateForm()
        return render_template('account/usercenter-info/usercenter-info.html', form=form, user=user)
    else:
        form = UserUpdateForm(formdata=request.form)
        if form.validate():
            from apps.ext import images, get_file_name
            # 判断用户是否重新上传头像
            if 'img' in request.files:
                image = request.files['img']
                file_name = images.save(image, folder='', name=get_file_name(image.filename))
                img_url = images.url(file_name)
                form.update_user(user, img_url)
            else:
                form.update_user(user)
        return render_template('account/usercenter-info/usercenter-info.html', form=form, user=user,
                               errors=form.errors.values())


@account.route("update", methods=['GET', 'POST'])
def update():
    user_session = session.get('user')
    user = User.query.get(user_session['user_id'])
    if request.method == 'GET':
        form = UpdatePasswordForm()
        return render_template('account/usercenter-info/user_password.html', form=form)
    else:
        form = UpdatePasswordForm(formdata=request.form)
        if form.validate():
            if user.password == form.old_password.data:
                form.update_password(user)
            else:
                form.errors["error_password"] = ["账号密码错误"]
        return render_template('account/usercenter-info/user_password.html', form=form,errors=form.errors.values())


@account.route("/mystore/", methods=['GET', 'POST'])
def store():
    user = session.get('user')
    if request.method == 'GET':
        user = User.query.filter_by(user_id=user['user_id']).first()
        store_num = user.store_num
        store_news = user.have_store
        return render_template('account/usercenter-info/mystore.html', store_num=store_num, news=store_news)
    else:
        new_id = request.form.get('new_id')
        user = User.query.filter_by(user_id=user['user_id']).first()
        user.store_num -= 1
        new = News.query.get(new_id)
        user.have_store.remove(new)
        db.session.commit()
        return flask.jsonify({"status": "success"})
